import { ExpertAddress } from '@/api/expert';
import { Button } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import { useState } from 'react';
import { useRequest } from 'taro-hooks';
import useEdit from '../address/components/useEdit';

export default function Page() {
  const { data: list, refresh } = useRequest(ExpertAddress, {
    cacheKey: 'get:address',
  });
  const [checked, setChecked] = useState<string | number>();
  const { renderNode: renderEditAddressNode, open: openEdit } = useEdit({
    onSuccess: function () {
      refresh();
    },
  });

  return (
    <>
      <View className=' min-h-screen bg-white pt-4'>
        {list?.map((item) => (
          <View
            key={item.id}
            onClick={() => {
              setChecked(item.id);

              //获取上一页的页面栈
              const pages = Taro.getCurrentPages();
              const prevPage = pages[pages.length - 2];
              prevPage.data.selectAddress = item;
              Taro.navigateBack();
            }}
            className={classNames(
              'flex p-4 border-4 border-solid border-gary5 rounded-lg mx-4 mb-3'
            )}
          >
            <View
              className=' w-5 h-5 bg-cover mr-2'
              style={{
                backgroundImage: `url(${
                  item.id === checked
                    ? 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-checked.svg'
                    : 'https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-address.svg'
                })`,
              }}
            ></View>
            <Text className={classNames('flex-1 text-sm font-bold text-gary4')}>
              {item.address}
            </Text>
          </View>
        ))}

        <View className=' p-4 fixed left-0 right-0 bottom-0'>
          <Button type='primary' block onClick={() => openEdit()}>
            添加地址
          </Button>
        </View>
      </View>

      {renderEditAddressNode()}
    </>
  );
}
